package com.jlanglang.glide.loaderdemo.loader

import com.bumptech.glide.Priority
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.Options
import com.bumptech.glide.load.data.DataFetcher
import com.bumptech.glide.load.model.ModelLoader
import com.bumptech.glide.signature.ObjectKey
import com.jlanglang.glide.loaderdemo.util.DESUtil
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStream

class FileModelLoader : ModelLoader<File, InputStream> {

    override fun buildLoadData(model: File, width: Int, height: Int,
                               options: Options): ModelLoader.LoadData<InputStream>? {
        return ModelLoader.LoadData(ObjectKey(model),
            FileDataFetcher(model)
        )
    }

    override fun handles(file: File): Boolean {
        return true
    }
}


/**
 * 如何加载数据
 */
class FileDataFetcher(private val file: File?) : DataFetcher<InputStream> {
    private var mInputStream: InputStream? = null

    override fun loadData(priority: Priority,
                          callback: DataFetcher.DataCallback<in InputStream>) {
           file ?: return
           // 最主要就是在这里做加密和解密的操作
           mInputStream = FileInputStream(file)
           // 解密,密码为"12345678"
           mInputStream = DESUtil.decodeInputStream(mInputStream,"12345678")
           // 这里返回已经解密好的输入流
           callback.onDataReady(mInputStream)
    }
    //这里是用来释放IO流的
    override fun cleanup() {
        try {
            mInputStream?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    override fun cancel() {}

    override fun getDataClass(): Class<InputStream> {
        return InputStream::class.java
    }
    // 这里是默认的缓存类型
    override fun getDataSource(): DataSource {
        return DataSource.LOCAL
    }
}